<?php
declare (strict_types=1);

namespace app\api\controller;

use app\api\controller\Base;
use app\common\model\GoodsList;
use app\common\model\OrderList;
use app\common\model\User;
use app\common\model\Order;
use think\facade\Db;
use \think\Request;

class Market extends Base
{
    /**
     * 集市列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function market_list(Request $request)
    {
        $type = \request()->param('type', 1);

        $user = $this->getUser();
        $where = [];
        if ($type == 1) {
            //集市列表
            $where[] = ['a.status', '=', 0];
        } elseif ($type == 2) {
            //所有已成交
            $where[] = ['a.status', '=', 1];
        } elseif ($type == 3) {
            //我发布的
            $where[] = ['a.status', '=', 0];
            $where[] = ['a.user_id', '=', $user['id']];
        }

        $field = 'a.id,a.user_id,a.order_num,a.price,a.order_list_ids,a.status,a.addtime,b.nickname,b.headimg';
        $list = Db::name('market')
            ->alias('a')
            ->join('user b', 'a.user_id = b.id', 'left')
            ->field($field)
            ->where($where)
            ->order('a.id desc')
            ->paginate(['list_rows' => 15, 'query' => request()->param()])->each(function ($item) {
                $item['headimg'] = imageUrl($item['headimg']);
                $item['addtime'] = date('Y-m-d H:i:s', $item['addtime']);

                $orderlist = OrderList::field("goodslist_title,goodslist_imgurl,goodslist_money,goods_id,shang_id,prize_code,count(id) as prize_num")
                    ->append(['shang_title'])
                    ->whereIn('id', explode(',', $item['order_list_ids']))
                    ->order('shang_id asc')
                    ->withAttr('goodslist_imgurl', function ($value, $data) {
                        return imageUrl($value);
                    })
                    ->withAttr('goodslist_money', function ($value, $data) {
                        return (float)$value;
                    })
                    ->group("prize_code")
                    ->select()->toArray();
                $item['orderlist'] = $orderlist;
                $orderlist_total = array_sum(array_column($orderlist, 'prize_num'));
                $item['orderlist_total'] = $orderlist_total;
                return $item;
            });
        $page = $list->render();
        $data['list'] = $list->toArray()['data'];
        $data['count'] = $list->total();
        $data['last_page'] = $list->toArray()['last_page'];
        $data['page'] = $page;

        return $this->renderSuccess('请求成功', $data);
    }

//    /**
//     * 成交记录
//     * @param Request $request
//     * @return mixed
//     * @throws \think\db\exception\DbException
//     */
//    public function my_market_list(Request $request){
//        $user = $this->getUser();
//        $field = 'a.id,a.user_id,a.order_num,a.price,a.order_list_ids,a.status,a.addtime,b.nickname,b.headimg';
//        $list = Db::name('market_order')
//            ->alias('a')
//            ->join('user b','a.user_id = b.id','left')
//            ->field($field)
//            ->where([['a.status','=',2]])
//            ->order('a.id desc')
//            ->paginate(['list_rows' => 15, 'query' => request()->param()])->each(function ($item){
//                $item['headimg'] = imageUrl($item['headimg']);
//                $item['addtime'] = date('Y-m-d H:i:s',$item['addtime']);
//
//                $orderlist = OrderList::field("goodslist_title,goodslist_imgurl,goodslist_money,goods_id,shang_id,prize_code,count(id) as prize_num")
//                    ->append(['shang_title'])
//                    ->whereIn('id',explode(',',$item['order_list_ids']))
//                    ->order('shang_id asc')
//                    ->withAttr('goodslist_imgurl', function ($value, $data) {
//                        return imageUrl($value);
//                    })
//                    ->withAttr('goodslist_money', function ($value, $data) {
//                        return (float)$value;
//                    })
//                    ->group("prize_code")
//                    ->select()->toArray();
//                $item['orderlist'] = $orderlist;
//                $orderlist_total = array_sum(array_column($orderlist, 'prize_num'));
//                $item['orderlist_total'] = $orderlist_total;
//                return $item;
//            });
//        $page = $list->render();
//        $data['list'] = $list->toArray()['data'];
//        $data['count'] = $list->total();
//        $data['last_page'] = $list->toArray()['last_page'];
//        $data['page'] = $page;
//
//        return $this->renderSuccess('请求成功',$data);
//    }

    /**
     * 计算选择的奖品
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function js_market_price(Request $request)
    {
        $user = $this->getUser();
        $user_id = $user['id'];
        $order_list_ids = \request()->param('order_list_ids', '');
        if (!$order_list_ids) {
            return $this->renderError("参数错误");
        }

        $order_list_ids = explode(',', trim($order_list_ids));
        if (empty($order_list_ids)) {
            return $this->renderError("参数错误!");
        }
        $order_list_ids = array_unique($order_list_ids);
        $config = getConfig('base');
        foreach ($order_list_ids as $k => $v) {
            $is_order_list = Db::name('order_list')->field('id,goodslist_money')->where([['id', '=', $v], ['status', '=', 0], ['user_id', '=', $user_id], ['insurance_is', '=', 0]])->find();
            if (!$is_order_list) {
                return $this->renderError("数据错误!");
            }
            if ($is_order_list['goodslist_money'] < $config['jishi_money_fa']) {
                return $this->renderError("奖品价值低于" . $config['jishi_money_fa'] . "禁止发布");
            }
        }

        $orderlist = OrderList::field("goodslist_title,goodslist_imgurl,goodslist_money,goods_id,shang_id,prize_code,count(id) as prize_num")
            ->append(['shang_title'])
            ->where('user_id', '=', $user_id)
            ->where('status', '=', 0)
            ->where('insurance_is', '=', 0)
            ->whereIn('id', $order_list_ids)
            ->order('shang_id asc')
            ->withAttr('goodslist_imgurl', function ($value, $data) {
                return imageUrl($value);
            })
            ->withAttr('goodslist_money', function ($value, $data) {
                return (float)$value;
            })
            ->group("prize_code")
            ->select()->toArray();
        foreach ($orderlist as $k => $v) {
            if ($v['prize_num'] > 1) {
                return $this->renderError("同一种奖品,只能选择一个!");
            }
        }
        $orderlist_total = array_sum(array_column($orderlist, 'prize_num'));
        $orderlist_total_money = array_sum(array_column($orderlist, 'goodslist_money'));

        $jishi_money_zhe = $config['jishi_money_zhe'];
        if ($jishi_money_zhe && $jishi_money_zhe > 0) {
            $jishi_money_zhe = $jishi_money_zhe / 10;
            $orderlist_total_money = round($orderlist_total_money * $jishi_money_zhe, 2);
        }
        $data = [];
        $data['orderlist'] = $orderlist;
        $data['orderlist_total'] = $orderlist_total;
        $data['orderlist_total_money'] = $orderlist_total_money;

        return $this->renderSuccess('请求成功', $data);
    }

    /**
     * 发布集市
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function market_fa(Request $request)
    {
        $user = $this->getUser();
        $user_id = $user['id'];
        $order_list_ids = \request()->param('order_list_ids', '');
        $price = \request()->param('price', 0);
        $price = floatval($price);
        if (!$order_list_ids) {
            return $this->renderError("参数错误");
        }
        if (!$price || $price <= 0) {
            return $this->renderError("价格设置错误");
        }

        $order_list_ids = explode(',', trim($order_list_ids));
        if (empty($order_list_ids)) {
            return $this->renderError("参数错误!");
        }
        $order_list_ids = array_unique($order_list_ids);
        $config = getConfig('base');
        foreach ($order_list_ids as $k => $v) {
            $is_order_list = Db::name('order_list')->field('id,goodslist_money')->where([['id', '=', $v], ['status', '=', 0], ['user_id', '=', $user_id], ['insurance_is', '=', 0]])->find();
            if (!$is_order_list) {
                return $this->renderError("数据错误!");
            }
            if ($is_order_list['goodslist_money'] < $config['jishi_money_fa']) {
                return $this->renderError("奖品价值低于" . $config['jishi_money_fa'] . "禁止发布");
            }
        }

        $orderlist = OrderList::field("count(id) as prize_num")
            ->where('user_id', '=', $user_id)
            ->where('status', '=', 0)
            ->where('insurance_is', '=', 0)
            ->whereIn('id', $order_list_ids)
            ->order('shang_id asc')
            ->group("prize_code")
            ->select()->toArray();
        foreach ($orderlist as $k => $v) {
            if ($v['prize_num'] > 1) {
                return $this->renderError("同一种奖品,只能选择一个!");
            }
        }

        Db::startTrans();
        $data = [];
        $data['user_id'] = $user_id;
        $data['order_num'] = 'JS_' . $user_id . time();
        $data['price'] = $price;
        $data['order_list_ids'] = implode(',', $order_list_ids);
        $data['status'] = 0;
        $data['addtime'] = time();
        $data['update_time'] = time();
        $result = Db::name('market')->insert($data);

        $result2 = Db::name('order_list')->where([['status', '=', 0], ['user_id', '=', $user_id], ['insurance_is', '=', 0]])->whereIn('id', $order_list_ids)->update(['status' => 3]);
        if ($result && $result2) {
            Db::commit();
            return $this->renderSuccess("发布成功!");
        } else {
            Db::rollback();
            return $this->renderError("发布失败!");
        }
    }

    /**
     * 撤回
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function che_hui(Request $request)
    {
        $user = $this->getUser();
        $user_id = $user['id'];
        $market_id = \request()->param('id/d', 0);
        if (!$market_id) {
            return $this->renderError("参数错误");
        }
        $market = Db::name('market')->where([['id', '=', $market_id], ['user_id', '=', $user_id]])->whereNull('deltime')->find();
        if (!$market) {
            return $this->renderError("数据错误");
        }
        if ($market['status'] != 0) {
            return $this->renderError("已经被别人买走了");
        }

        $order_list_ids = explode(',', $market['order_list_ids']);

        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis_key = "market_pay" . '_' . $market_id;
        $redis_key_info = $redis->get($redis_key);
        if ($redis_key_info) {
            return $this->renderError("人数太多了,请稍后");
        } else {
            $redis->set($redis_key, 1, 20);
        }

        Db::startTrans();
        try {
            $result = Db::name('market')->where([['id', '=', $market_id], ['user_id', '=', $user_id]])->update(['status' => 2]);
            $result2 = Db::name('order_list')->where([['user_id', '=', $user_id]])->whereIn('id', $order_list_ids)->update(['status' => 0]);

            if ($result && $result2) {
                Db::commit();
                return $this->renderSuccess("撤回成功!");
            } else {
                Db::rollback();
                return $this->renderError("撤回失败!");
            }
        } catch (\Exception $e) {
            Db::rollback();
            return $this->renderError("撤回失败!!");
        }
    }

    /**
     * 计算支付价格
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function market_money(Request $request)
    {
        $user = $this->getUser();
        $user_id = $user['id'];
        $market_id = \request()->param('id/d', 0);
        $use_money_is = request()->param('use_money_is/d', 0);       #0不抵扣 1抵扣
        if (!$market_id) {
            return $this->renderError("参数错误");
        }
        $market = Db::name('market')->where('id', $market_id)->whereNull('deltime')->find();
        if (!$market) {
            return $this->renderError("数据错误");
        }
        if ($market['status'] != 0) {
            return $this->renderError("已经被别人买走了");
        }
        $price = $market['price'];

        $orderlist = OrderList::field("goodslist_title,goodslist_imgurl,goodslist_money,goods_id,shang_id,prize_code,count(id) as prize_num")
            ->append(['shang_title'])
            ->whereIn('id', explode(',', $market['order_list_ids']))
            ->order('shang_id asc')
            ->withAttr('goodslist_imgurl', function ($value, $data) {
                return imageUrl($value);
            })
            ->withAttr('goodslist_money', function ($value, $data) {
                return (float)$value;
            })
            ->group("prize_code")
            ->select()->toArray();

        #市集余额抵扣
        $use_money = 0;
        if ($use_money_is == 1) {
            if ($user['money2'] >= $price) {
                $use_money = $price;
                $price = 0;
            } else {
                $use_money = $user['money2'];#
                $price = bcsub("$price", "{$user['money2']}", 2);
            }
        }

        $data = [];
        $data['orderlist'] = $orderlist;
        $data['money'] = $user['money2'];
        $data['use_money'] = $use_money;
        $data['price'] = $price;

        return $this->renderSuccess('请求成功', $data);
    }

    public function market_pay(Request $request)
    {
        $user = $this->getUser();
        $user_id = $user['id'];
        $market_id = request()->param('id/d', 0);
        $use_money_is = request()->param('use_money_is/d', 0);       #0不抵扣 1抵扣

        if (!$market_id) {
            return $this->renderError("参数错误");
        }
        $market = Db::name('market')->where('id', $market_id)->whereNull('deltime')->find();
        if (!$market) {
            return $this->renderError("数据错误");
        }
        if ($market['user_id'] == $user_id) {
            return $this->renderError("不能购买自己发布的");
        }
        if ($market['status'] != 0) {
            return $this->renderError("已经被别人买走了");
        }

        $price = $market['price'];

        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis_key = "market_pay" . '_' . $market_id;
        $redis_key_info = $redis->get($redis_key);
        if ($redis_key_info) {
            return $this->renderError("人数太多了,请稍后");
        } else {
            $redis->set($redis_key, 1, 20);
        }

        #市集余额抵扣
        $use_money = 0;
        if ($use_money_is == 1) {
            if ($user['money2'] >= $price) {
                $use_money = $price;
                $price = 0;
            } else {
                $use_money = $user['money2'];#
                $price = bcsub("$price", "{$user['money2']}", 2);
            }
        }

        $order_num = create_order_no('MH_', 'order', 'order_num');
        $data = [];;
        $data['market_id'] = $market_id;
        $data['user_id'] = $user_id;
        $data['order_num'] = $order_num;
        $data['price'] = $market['price'];
        $data['order_list_ids'] = $market['order_list_ids'];
        $data['status'] = 1;
        $data['total'] = $market['price'];
        $data['total_price'] = $price;
        $data['money'] = $use_money;
        $data['addtime'] = time();
        $data['update_time'] = time();
        $market_order_id = Db::name('market_order')->insertGetId($data);
        if ($price > 0) {
            $body = '集市购买';
            $attach = 'order_js';
            $payRes = (new Pay())->wxCreateOrder($order_num, $price, $user['openid'], $body, $attach);
            if ($payRes['status'] == 1) {
                $new_data = [
                    'status' => 1,
                    'res' => $payRes['data'],
                ];
                return $this->renderSuccess("购买成功", $new_data);
            }
            return $this->renderError("人数过多,请稍后再试");
        } else {
            $result = (new Notify($this->app))->update_js_order($market_order_id);
            if ($result == 1) {
                return $this->renderSuccess("购买成功");
            } else {
                Db::name('market_order')->where('id', $market_order_id)->update(['status' => 3, 'update_time' => time()]);
                return $this->renderError("人数过多,请稍后再试");
            }
        }
    }


}
